import * as CatApi from '@lib/api/category';
import withReduxStore from '@lib/with-redux-store';
import { setCategory } from '@store/action/category';
import App, { Container } from 'next/app';
import React from 'react';
import { Provider } from 'react-redux';

class MyApp extends App<any, any> {
	public static async getInitialProps(context: any) {
		const initialProps = await App.getInitialProps(context);
		if (!context.ctx.reduxStore.getState().category.length) {
			const category = await CatApi.List();
			if (!(category instanceof Error)) {
				context.ctx.reduxStore.dispatch(setCategory(category.list));
			}
		}
		return initialProps;
	}

	public componentDidMount() {
		if (typeof(window._hmt) === "undefined") {
			window._hmt = [];
		}
		const hm = document.createElement("script");
		hm.src = "https://hm.baidu.com/hm.js?964e6c85881afa4ed3d6bbfcbe4bac27";
		document.body.appendChild(hm);
	}

	public render() {
		const { Component, pageProps, reduxStore } = this.props
		return (
			<Container>
				<Provider store={reduxStore}>
					<Component {...pageProps} />
				</Provider>
			</Container>
		)
	}
}

export default withReduxStore(MyApp)